import numpy as np
import cv2
# 图像查找

img1 = cv2.imread("C:\\Users\\86191\\Pictures\\Saved Pictures\\Camera Roll\\op4.jpg")
img2 = cv2.imread("C:\\Users\\86191\\Pictures\\Saved Pictures\\Camera Roll\\op1.jpg")
# 灰度化
g1 = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)
g2 = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)
# 创建sift对象
sift = cv2.SIFT_create()
# 计算描述子
kp1,des1= sift.detectAndCompute(g1,None)
kp2,des2= sift.detectAndCompute(g2,None)
# 创建特征匹配器
index_params = dict(algorithm=1, trees=5)
search_params = dict(checks = 50)
flann = cv2.FlannBasedMatcher(index_params,search_params)
# 匹配
match = flann.knnMatch(des1,des2,k=2)
# 筛选特征点
good = []
for i,(m,n) in enumerate(match):
    if m.distance < 0.7*n.distance:
        good.append(m)


if len(good) >= 4:
    srcPts = np.float32([kp1[m.queryIdx].pt for m in good]).reshape(-1,1,2)
    dstPts = np.float32([kp2[m.trainIdx].pt for m in good]).reshape(-1,1,2)
    H, _ = cv2.findHomography(srcPts, dstPts, cv2.RANSAC,5.0)
    # 寻找角点绘制矩形
    h,w = img1.shape[:2]
    pst = np.float32([[0,0],[0,h-1],[w-1,h-1],[w-1,0]]).reshape(-1,1,2)
    #进行透视变换。通过将输入的坐标点集pst与变换矩阵H相乘，得到变换后的坐标点集dst。
    dst = cv2.perspectiveTransform(pst,H)
    cv2.polylines(img2,[np.int32(dst)],True,(0,0,255),3)
else:
    exit()

ret = cv2.drawMatchesKnn(img1,kp1,img2,kp2,[good],None)
cv2.imshow("result",ret)
cv2.waitKey(0)